package Redis

import (
	"context"
	"fmt"
	"forum/app/config"
	"log"

	"github.com/go-redis/redis/v8"
)

var (
	RedisClient *redis.Client
	redisCtx    = context.Background()
)

// InitRedis 初始化 Redis 连接
func InitRedis() {
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", config.RedisConfig.Host, config.RedisConfig.Port),
		Password: config.RedisConfig.Password,
		DB:       config.RedisConfig.DB,
	})

	// 测试连接
	_, err := RedisClient.Ping(redisCtx).Result()
	if err != nil {
		log.Fatalf("Failed to connect to Redis: %v", err)
	}

	fmt.Println("Redis connected successfully")
}

// GetRedisClient 获取 Redis 客户端实例
func GetRedisClient() *redis.Client {
	return RedisClient
}

// CloseRedis 关闭 Redis 连接
func CloseRedis() {
	if RedisClient != nil {
		err := RedisClient.Close()
		if err != nil {
			log.Printf("Error closing Redis connection: %v", err)
		}
	}
}
